<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row>
        <el-button type="primary" @click="addrolesVisiable = true">添加</el-button>
      </el-row>
      <!-- 数据列表 -->
      <el-table
        :data="rolesList"
        border
        stripe
        style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot:default="scope">
            <!-- 第一层数据 -->
            <el-row class="bdbottom vcontent" :class="{bdtop:index1 === 0}" v-for="(item1,index1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag closable @close="removeRight(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 第二级权限 -->
                <el-row class="vcontent" :class="{bdtop:index2 !== 0}" v-for="(item2,index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRight(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 第三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" closable @close="removeRight(scope.row,item3.id)" v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引值 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述">
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column
          label="操作">
          <template v-slot:default="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getrolesById(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRoles(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="getRolesTree(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addrolesVisiable"
      width="30%" @close="colseaddRolesDialog">
      <!-- 添加角色内容区域 -->
      <el-form ref="addRolesFormRef" :model="addRolesForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addrolesVisiable = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editrolesVisiable"
      @close="colseEditDialog"
      width="30%">
      <!-- 添加角色内容区域 -->
      <el-form ref="editRolesFormRef" :model="editRolesForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editrolesVisiable = false">取 消</el-button>
        <el-button type="primary" @click="subeditRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限分配对话框 -->
    <el-dialog
      title="权限分配"
      :visible.sync="setRightsVisiable"
      width="50%" @close="colserightDialog">
      <!-- 权限分配内容 -->
      <el-tree :data="rolesListt" :props="rolesprops" show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys" ref="rolesRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsVisiable = false">取 消</el-button>
        <el-button type="primary" @click="subRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getdata} from '../../network/getdata'
export default {
  name:'roles',
  data() {
    return {
      //角色列表数据
      rolesList:[],
      //添加角色对话框显示与隐藏  -- false 隐藏
      addrolesVisiable:false,
      //添加角色对象
      addRolesForm:{
        roleName:'',
        roleDesc:''
      },
      addFormRules:{
        roleName:[
          {required:true,message:'请输入角色名称',triiger:'blur'},
          {min:3,max:10,message:'长度在 3 到 10 个字符之间',trigger:'blur'}
        ],
        roleDesc:[
          {required:true,message:'请输入角色描述',trigger:'blur'}
        ]
      },
      //编辑信息对话框的显示与隐藏
      editrolesVisiable:false,
      //编辑角色对话框信息
      editRolesForm:{},
      addFormRules:{
        roleName:[
          {required:true,message:'请输入角色名称',trigger:'blur'}
        ],
        roleDesc:[
          {required:true,message:'请输入角色描述',trigger:'blur'}
        ]
      },
      // 权限分配对话框的显示与隐藏 false 隐藏
      setRightsVisiable:false,
      // 所有权限列表
      rolesListt:[],
      // 树形控件的属性绑定对象
      rolesprops:{
        label:'authName',
        children:'children'
      },
      //默认选中的 key 的数组
      defkeys:[],
      // 当前即将要修改权限的角色id
      roleId:''
    }
  },
  methods: {
    //提交分配好的当前用户的权限
    subRights() {
      // 获取被选中的节点的 id 
      const keys = [...this.$refs.rolesRef.getCheckedKeys(),...this.$refs.rolesRef.getHalfCheckedKeys()]
      //将选中和半选中状态的 id 数组转换为 以 , 分割的字符串
      const ids = keys.join(',')
      console.log(ids)
      getdata({
        method:'post',
        url:`roles/${this.roleId}/rights`,
        data:{
          rids:ids
        }
      }).then((result) => {
        const res = result.data
        if(res.meta.status !== 200) {
          this.$message.error('分配权限失败')
          return ;
        }
        //分配权限成功
        this.$message.success('分配权限成功')
        //更新列表
        this.getRolesList();
        //关闭窗口
        this.setRightsVisiable = false
      })
    },
    //关闭权限分配的对话框
    colserightDialog() {
      //清空默认选中的 id 数组 便面下次获取数据混乱
      //重置 defkeys 的 值
      this.defkeys = []
    },
    //递归获取第三级权限的id
    getleafdefkeys(node,arr){
      //递归退出的条件
      if(!node.children) {
        //没有 children属性 说明是第三级节点
        return arr.push(node.id)
      }
      //如果不是第三级的节点
      node.children.forEach((item) => {
        return this.getleafdefkeys(item,arr)
      });
    },
    //获取权限列表
    getRolesTree(row) {
      getdata({
        method:'get',
        url:`rights/tree`
      }).then((result) => {
        const res = result.data
        if(res.meta.status !== 200) {
          this.$message.error('获取权限列表失败')
          return ;
        }
        this.rolesListt = res.data
        //获取默认展开选中的数据
        this.getleafdefkeys(row,this.defkeys)
        // console.log(this.defkeys)
        // 保存当前角色的id 给 后续提交的选中的权限使用
        this.roleId = row.id
        this.setRightsVisiable = true
        // console.log(this.rolesListt)

      })
    },
    //删除权限
    removeRight(role,rightId) {
      //是否确定删除
      this.$confirm('此操作将永久取消该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //确定要删除
          getdata({
            method:'delete',
            url:`roles/${role.id}/rights/${rightId}`
          }).then((result) => {
            const res = result.data
            if(res.meta.status !== 200) {
              this.$message.error('取消权限失败')
              return ;
            }
            //取消权限成功
            //为了避免重新刷新数据当前行会合上,将返回的数据赋值给当前行
            role.children = res.data
          })
        }).catch(() => {
          //取消
          this.$message.info('已取消操作')
          return ;
        })
    },
    //删除用户
    delRoles(id) {
      this.$confirm('操作会永久删除该角色,是否继续','温馨提醒',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type: 'warning'
      }).then(() => {
        //确定删除
        getdata({
          method:'delete',
          url:`roles/${id}`
        }).then((result) => {
          const res = result.data
          if(res.meta.status !== 200) {
            //删除失败
            this.$message.error('删除失败')
            return ;
          }
          //删除成功
          this.$message.success('已删除该角色')
          this.getRolesList()
        })
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },
    //提交编辑信息
    subeditRoles() {
      //先对数据进行校验
      this.$refs.editRolesFormRef.validate((valid) => {
        if(!valid) {
          //输入不合法
          return ;
        }
        //数据合法发起请求
        const params = {
          roleName:this.editRolesForm.roleName,
          roleDesc:this.editRolesForm.roleDesc
        }
        getdata({
          method:'put',
          url:`/roles/${this.editRolesForm.roleId}`,
          data:params
        }).then(result => {
          const res = result.data
          if(res.meta.status !== 200) {
            //修改失败
            this.$message.error(res.meta.msg)
            return ;
          }
          //修改成功 关闭对话框 刷新数据
          this.$message.success('修改成功')
          this.editrolesVisiable = false
          this.getRolesList()
        })
      })
    },
    //关闭编辑对话框并清空校验
    colseEditDialog() {
      this.$refs.editRolesFormRef.resetFields()
    },
    //根据 id 获取角色信息
    getrolesById(id){
      getdata({
        method:'get',
        url:`roles/${id}`
      }).then(result => {
        const res = result.data
        this.editRolesForm = res.data
        this.editrolesVisiable = true
      })
    },
    //添加用户
    addRoles() {
      //相对用户进行校验
      this.$refs.addRolesFormRef.validate((valid) => {
        if(!valid) {
          //用户输入不合法
          return ;
        }
        //数据合法 发起请求
        getdata({
          method:'post',
          url:'/roles',
          data:this.addRolesForm
        }).then((result) => {
          const res = result.data
          if(res.meta.status !== 201){
            //添加失败
            this.$message.error('添加角色失败')
            return ;
          }
          //添加角色成功 刷新数据 关闭窗口
          this.$message.success('添加角色成功')
          this.addrolesVisiable = false
          this.getRolesList()
        })
      })
    },
    //关闭添加对话框 重置数据并清空校验
    colseaddRolesDialog() {
      this.$refs.addRolesFormRef.resetFields()
    },
    //获取角色列表
    getRolesList() {
      getdata({
        method:'get',
        url:'/roles'
      }).then((result) => {
        const res = result.data
        if(res.meta.status !== 200) {
          //获取角色列表失败
          this.$message.error(res.meta.msg);
        }
        //获取数据成功
        this.rolesList = res.data
        // console.log(this.rolesList)
      })
    }
  },
  created() {
    this.getRolesList()
  },
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
// 垂直居中显示
.vcontent {
  display: flex;
  align-items: center;
}
</style>